package cn.com.se.sharepictrue.widget;

import android.content.Context;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;

public class AdapterLinearLayout extends LinearLayoutCompat {

    private RecyclerView.Adapter mAdapter;

    private RecyclerView.AdapterDataObserver dataSetObserver = new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            reloadChildViews();
        }
    };

    public AdapterLinearLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public AdapterLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AdapterLinearLayout(Context context) {
        super(context);
    }

    public void setAdapter(RecyclerView.Adapter adapter) {
        if (this.mAdapter == adapter) {
            return;
        }
        this.mAdapter = adapter;
        adapter.registerAdapterDataObserver(dataSetObserver);
        reloadChildViews();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mAdapter != null && mAdapter.hasObservers()) {
            mAdapter.unregisterAdapterDataObserver(dataSetObserver);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private void reloadChildViews() {
        removeAllViews();

        if (mAdapter == null || mAdapter.getItemCount() == 0) {
            return;
        }

        int count = mAdapter.getItemCount();
        for (int position = 0; position < count; ++position) {
            RecyclerView.ViewHolder holder = mAdapter.createViewHolder(this, mAdapter.getItemViewType(position));
            mAdapter.bindViewHolder(holder, position);
            View v = holder.itemView;
            if (v != null) {
                addView(v);
            }
        }
        requestLayout();
    }
}